package com.yzd.netmonitor.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类.
 * @version 1.0.0
 * @see 1.0.0
 *
 */
public final class TimeHelper {
	public static final String  DATEFORMAT_YYYY_MM_dd_HH_mm_ss= "yyyy-MM-dd HH:mm:ss";
	public static final String  DATEFORMAT_YYYY_MM_dd= "yyyy-MM-dd";
	/**
	 * 根据日期及格式, 格式化日期为字符串.
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String getTime(final Date date) {
		final DateFormat df = new SimpleDateFormat(DATEFORMAT_YYYY_MM_dd_HH_mm_ss);
		return df.format(date);
	}

	public static String getTime1(final Date date, final String pattern) {
		final DateFormat df = new SimpleDateFormat(pattern);
		return df.format(date);
	}
	
	/**
	 * 时间的转换.
	 * @param date
	 * @return
	 */
	public static Date getDate(final String date) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return df.parse(date);
		} catch (ParseException e) {
			throw new IllegalStateException("生日格式不正确", e);
		}
	}
	
	/**
	 * 时间的转换.
	 * @param date
	 * @return
	 */
	public static Date getDate(final String date,String format) {
		DateFormat df = new SimpleDateFormat(format);
		try {
			return df.parse(date);
		} catch (ParseException e) {
			throw new IllegalStateException("生日格式不正确", e);
		}
	}

	/**
	 * 获取几天前或几天后的日期.
	 * 
	 * @param day
	 *            可为负数,为负数时代表获取之前的日期.为正数,代表获取之后的日期
	 * @return
	 */
	public static Date getDate(final int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + day);
		return calendar.getTime();
	}

	/**
	 * 获取指定的日期. 可为年、月、日等
	 * 
	 * @param field
	 * @return
	 */
	public static int get(final int field) {
		return Calendar.getInstance().get(field);
	}

	/**
	 * 计算年龄.
	 * @author YRJ
	 *
	 */
	public static int getAge(final Date birthday) {
		return getAge(birthday, new Date());
	}

	/**
	 * 计算年龄
	 * @author YRJ
	 *
	 */
	public static int getAge(final Date birthday, final Date endDay) {
		Calendar born = Calendar.getInstance();
		Calendar now = Calendar.getInstance();

		if (birthday != null) {
			born.setTime(birthday);
			now.setTime(endDay);
		}

		if (now.before(born)) {
			return 0;//年龄错误.
		}

		int age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
		if (now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
			age -= 1;
		}
		return age;
	}

	private TimeHelper() {
		throw new AssertionError("Uninstantiable class.");
	}
}
